package com.cms.biz.products;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cms.bean.ProductBean;
import com.cms.config.CategoryTypeDef;
import com.cms.config.ConfigDef;
import com.cms.database.DBHelper;
import com.cms.facade.RequestFacade;
import com.cms.facade.SessionFacade;
import com.cms.framework.Command;
import com.cms.framework.CommandException;
import com.cms.framework.CommandToken;
import com.cms.util.FileHelper;
import com.cms.util.StringHelper;

public class AddProductCommand implements Command {
	
	private String next;
	public AddProductCommand(String next) {
		this.next = next;
	}

	@SuppressWarnings("finally")
	@Override
	public String execute(HttpServletRequest req) throws CommandException {
		HttpSession session = req.getSession();
		Connection conn = DBHelper.getConn();
		
		if (!CommandToken.isValid(req)) {
			RequestFacade.setSuccessFlag(req, Boolean.FALSE);
			RequestFacade.setInvalidTokenMsg(req);
			return next;
		}
		
		int productid = StringHelper.isRequestParamEmptyInt(req, "productId", 0);
		int category = StringHelper.isRequestParamEmptyInt(req, "category", CategoryTypeDef.PRODUCT);
		int subcategory = StringHelper.isRequestParamEmptyInt(req, "subcategory", -1);
		int specialId = StringHelper.isRequestParamEmptyInt(req, "specialId", 0);
		int picNum = StringHelper.isRequestParamEmptyInt(req, "picNum", 0);
		String title = StringHelper.isEmpty(req.getParameter("title"), "");
		String content = StringHelper.isEmpty(req.getParameter("content"), "");
        String userId = SessionFacade.getUser(session);
		
        try {
        	
        	ProductBean pBean = new ProductBean();
        	pBean.setId(productid);
        	pBean.setTitle(title);
        	pBean.setFolderId(ConfigDef.ACTIVE);
        	pBean.setCategoryId(category);
        	pBean.setSubCategoryId(subcategory);
        	pBean.setSpecialId(specialId);
        	pBean.setPicNum(picNum);
        	pBean.setIspassd(ConfigDef.NOT_AUDIT);
        	pBean.setCreateUser(userId);
        	
        	String htmlPath = FileHelper.getProductContentHTMLPath(productid);
        	FileHelper.writeRSFContentFile(content, htmlPath);
        	ProductHelper.AddProduct(conn, pBean);
        	
        	RequestFacade.setSuccessFlag(req, Boolean.TRUE);
        	
        }catch(Exception e){
        	e.printStackTrace();
			RequestFacade.setSuccessFlag(req, Boolean.FALSE);
			RequestFacade.setErrorMsg(req, e.getMessage());
        }finally{
			DBHelper.closeConn(conn);
			return next;
        }

	}

}
